package net.imagine.provider.skyline;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.FastHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;

public class BaseDispatchAction {
	protected Object actionInstance;
	@SuppressWarnings("unchecked")
	protected Class clazz;
	private static final Log logger = LogFactory.getLog(BaseDispatchAction.class);

	protected FastHashMap methods;
	@SuppressWarnings("unchecked")
	protected Class[] types;
	protected String parameter;
	private static final String DEFAULT_PARAMETER = "method";

	public BaseDispatchAction() {
		methods = new FastHashMap();
		methods.setFast(true);
		types = new Class[] { HttpServletRequest.class, HttpServletResponse.class };
	}

	public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		if(!StringUtils.hasLength(parameter)) {
			parameter = DEFAULT_PARAMETER;
		}
		String methodName = request.getParameter(parameter);
		if(!StringUtils.hasLength(methodName)) {
			logger.warn("链接中没有"+parameter+"参数,地址或者配置不合法，执行execute");
			methodName = "execute";
		}
		Method method = getMethod(methodName);
		method.invoke(actionInstance, request, response);
	}

	@SuppressWarnings("unchecked")
	private Method getMethod(String name) throws NoSuchMethodException {
		Method method = (Method) this.methods.get(name);
		if (method == null) {
			method = this.clazz.getMethod(name, this.types);
			this.methods.put(name, method);
		}
		return method;
	}

	public void setActionInstance(Object actionInstance) {
		this.actionInstance = actionInstance;
	}

	@SuppressWarnings("unchecked")
	public void setClazz(Class clazz) {
		this.clazz = clazz;
	}

	public void setParameter(String parameter) {
		this.parameter = parameter;
	}
}
